import dht
from lib.clock import ticker_clock
from machine import Pin

"""
dht11温湿度传感器
"""

temp = -1
humidity = -1
dht11 = None


def read_dht11(pin):
    global temp, humidity, dht11
    if not dht11:
        dht11 = dht.DHT11(Pin(pin, Pin.IN))
    try:
        dht11.measure()
        temp = dht11.temperature()
        humidity = dht11.humidity()
        return temp, humidity
    except Exception as e:
        print("dht11 error:", e)


def print_dht11():
    print(f"Temperature : {temp:.1f}°C")
    print(f"Humidity    : {humidity:.1f}%")

if __name__ == "__main__":
    from lib.config.index import sensor_config

    config = sensor_config.get_sensor("ds18b20")

    pin_num = config["pin"]
    print("pin", pin_num)
    timer = ticker_clock.TickerClock(2000)
    while True:
        if timer.check():
            read_dht11(pin_num)
            print_dht11()
